import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:mi_mang_flutter/utils/utils.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

/// 右侧有删除按钮,发送验证码的文本框
class TextFieldSms extends StatefulWidget {
  final TextEditingController controller;

  final FocusNode? focusNode;

  /// 左侧标题文本
  final String title;

  /// 左侧标题样式
  final TextStyle? titleStyle;

  /// 提示文本内容
  final String hintText;

  /// 提示文本样式
  final TextStyle? hintStyle;

  /// 输入框文本样式
  final TextStyle? contentStyle;

  /// 运行文本框输入最大长度
  final int maxLength;

  /// 获取验证码
  final Function? getVCode;

  /// 电话号码
  final String? phone;

  /// 右侧文本框距左侧宽度
  final double spacing;

  /// 左侧文本最小宽度
  final double minWidth;

  TextFieldSms({
    Key? key,
    required this.controller,
    this.focusNode,
    this.title = "",
    this.titleStyle,
    this.hintText = "",
    this.hintStyle,
    this.contentStyle,
    this.maxLength = 16,
    this.getVCode,
    this.phone,
    this.spacing = 10.0,
    this.minWidth = 65.0,
  }) : super(key: key);

  @override
  _TextFieldSmsState createState() => _TextFieldSmsState();
}

class _TextFieldSmsState extends State<TextFieldSms> {
  bool _isShowDelete = true;
  bool _isClick = true;
  // bool _isAutoFocus = false;

  /// 倒计时秒数
  final int second = 30;

  /// 当前秒数
  late int s;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    //监听输入改变
    widget.controller.addListener(() {
      setState(() {
        _isShowDelete = widget.controller.text.isEmpty;
      });
    });
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Offstage(
          offstage: widget.title.isEmpty,
          child: Container(
            padding: EdgeInsets.only(right: widget.spacing),
            constraints: BoxConstraints(
              minWidth: widget.minWidth,
            ),
            child: Text(
              widget.title,
              style: widget.titleStyle ?? TextStyles.bodyMedium,
            ),
          ),
        ),
        Expanded(
          flex: 1,
          child: Localizations(
            locale: const Locale("en", ""),
            delegates: [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            child: TextField(
              focusNode: widget.focusNode,
              maxLength: widget.maxLength,
              controller: widget.controller,
              textInputAction: TextInputAction.done,
              keyboardType: TextInputType.number,
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.symmetric(vertical: 16.0),
                hintText: widget.hintText,
                counterText: "",
                focusedBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
              ),
            ),
          ),
        ),
        Offstage(
          offstage: _isShowDelete,
          child: InkWell(
            highlightColor: Colors.transparent,
            splashColor: Colors.transparent,
            child: loadImage(
              "public/close_icon",
              width: 18.0,
              height: 18.0,
            ),
            onTap: () {
              widget.controller.clear();
              widget.focusNode!.requestFocus();
            },
          ),
        ),
        Offstage(
          offstage: widget.getVCode == null,
          child: Padding(
            padding: const EdgeInsets.only(left: 15.0),
            child: Container(
              height: 28.0,
              child: TextButton(
                onPressed: _isClick ? _getVCode : null,
                style: TextButton.styleFrom(
                  padding: const EdgeInsetsDirectional.only(
                    start: 8.0,
                    end: 8.0,
                  ),
                  backgroundColor: Colors.transparent,
                ),
                child: Text(
                  _isClick ? "获取验证码" : "（${s}s）后重试",
                  style: TextStyles.bodyMedium,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 添加验证
  bool _oncheckedPhoneNumber() {
    String phone = widget.phone!;
    if (phone.isEmpty || !Utils.isPhone(phone)) {
      Toast.showWarn("请输入正确的手机号");
      return false;
    }
    return true;
  }

  /// 点击获取验证码
  _getVCode() {
    if (_oncheckedPhoneNumber()) {
      if (widget.focusNode != null) {
        widget.focusNode!.requestFocus();
      }
      widget.getVCode!();
      setState(() {
        s = second;
        _isClick = false;
      });

      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        setState(() {
          s = second - timer.tick;
          if (s < 1) {
            _isClick = true;
            _cancelTimer();
          }
        });
      });
    }
  }
}
